package com.scujj.cs6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scujj.cs6.common.BusinessException;
import com.scujj.cs6.common.ErrorCode;
import com.scujj.cs6.mapper.UserFavoriteMapper;
import com.scujj.cs6.model.entity.UserFavorite;
import com.scujj.cs6.model.vo.UserFavoriteVo;
import com.scujj.cs6.service.UserFavoriteService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author FlanChan
 * @description 针对表【user_favorite】的数据库操作Service实现
 * @createDate 2025-03-25 21:21:24
 */
@Service
@AllArgsConstructor
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite>
        implements UserFavoriteService {

    @Override
    public void favoriteAnswer(Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        UserFavorite userFavorite = new UserFavorite();
        if (this.count(new LambdaQueryWrapper<>(UserFavorite.class).eq(UserFavorite::getUserId,userId).eq(UserFavorite::getAnswerId,id)) > 0) {
            throw new BusinessException(ErrorCode.SERVER_ERROR,"已经收藏过该回答");
        }
        userFavorite.setAnswerId(id);
        userFavorite.setUserId(userId);
        this.save(userFavorite);
    }

    @Override
    public void cancelFavorite(Long id, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("user");
        LambdaQueryWrapper<UserFavorite> queryWrapper = new LambdaQueryWrapper<>(UserFavorite.class).eq(UserFavorite::getUserId, userId).eq(UserFavorite::getAnswerId, id);
        UserFavorite fav = this.getOne(queryWrapper);
        if (fav == null) {
            throw new BusinessException(ErrorCode.SERVER_ERROR,"收藏不存在");
        }
        this.remove(queryWrapper);
    }

    @Override
    public List<UserFavoriteVo> getFavorites(HttpServletRequest request) {
        return this.baseMapper.getFavorites((Long) request.getAttribute("user"));
    }
}




